package com.ecgsystem.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.ecgsystem.R;
import com.ecgsystem.constants.Constants;
import com.ecgsystem.listadapter.PatientListAdapter;
import com.ecgsystem.services.GetOnlinePatientsService;


/**
 * TODO Put here a description of what this class does.
 * 
 * @author ANHTUAN. Created Sep 28, 2012.
 */
public class PatientList extends Activity implements Constants {
	private ListView patientListView;
	private EditText searchTextEdit;

	private PatientListAdapter adapter;
	public static ArrayList<HashMap<String, String>> patientListArr;

	private EditText uSignalIDET;
	private Button QuickViewBT;

	private int pos;

	private Intent intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.patient_list);

		intent = new Intent(this, GetOnlinePatientsService.class);

		patientListArr = MainActivity.conn.getPatientList();

		this.patientListView = (ListView) findViewById(R.id.listView_patient_list);
		patientListView.setTextFilterEnabled(true);

		if (patientListArr != null) {
			adapter = new PatientListAdapter(this, patientListArr);

			this.patientListView.setAdapter(adapter);
		}
		this.patientListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				Intent i = new Intent(PatientList.this, PatientTab.class);

				pos = adapter.getPositionList()[position];

				i.putExtra("clickedposition", pos);
				startActivity(i);
				finish();
			}
		});

		this.searchTextEdit = (EditText) findViewById(R.id.editText_search);
		searchTextEdit.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable arg0) {
				// Do nothing
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// Do nothing
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				adapter.getFilter().filter(s);
			}

		});

		uSignalIDET = (EditText) findViewById(R.id.editText_UnusualSignalNo);

		QuickViewBT = (Button) findViewById(R.id.button_QuickView);
		QuickViewBT.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				String uSignalNo = uSignalIDET.getText().toString().trim();
				if (uSignalNo != null && !uSignalNo.equals("")) {
					OfflineECG.QueueDraw = (ConcurrentLinkedQueue<Float>[]) new ConcurrentLinkedQueue[12];
					for (int i = 0; i < 12; i++) {
						OfflineECG.QueueDraw[i] = new ConcurrentLinkedQueue<Float>();
					}

					HashMap<String, String> h = new HashMap<String, String>();
					h = MainActivity.conn.getInfobyUnusualSignalID(uSignalNo);
					Intent i = new Intent(PatientList.this, OfflineECG.class);
					i.putExtra(TAG_UNUSUALSIGNAL_ID, uSignalNo);
					i.putExtra(TAG_PATIENT_NAME, h.get(TAG_PATIENT_NAME));
					i.putExtra(TAG_PATIENT_ID, h.get(TAG_PATIENT_ID));
					i.putExtra(TAG_RECORD_ID, h.get(TAG_RECORD_ID));
					i.putExtra(TAG_RECORD_DATE, h.get(TAG_RECORD_DATE));

					startActivity(i);
				}
			}
		});
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_logout:
			Toast.makeText(PatientList.this, "Logout", Toast.LENGTH_SHORT)
					.show();

			// logout
			getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
					.remove(PREF_USERNAME).remove(PREF_PASSWORD).commit();

			System.exit(0);
			return true;
		case R.id.menu_conf:
			Bundle bundleConf = new Bundle();
			Intent intent = new Intent(PatientList.this, Configuration.class);
			intent.putExtras(bundleConf);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			unregisterReceiver(broadcastReceiver);
			stopService(intent);
			
			System.exit(0);
		}
		return false;
	}

	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			updateUI(intent);
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		startService(intent);
		Log.d("onResume", "onresume");
		registerReceiver(broadcastReceiver, new IntentFilter(
				GetOnlinePatientsService.BROADCAST_ACTION));
	}

	@Override
	public void onPause() {
		super.onPause();
		unregisterReceiver(broadcastReceiver);
		stopService(intent);
	}

	private void updateUI(Intent intent) {
		int count = intent.getIntExtra("COUNT", 0);
		String list[] = intent.getStringArrayExtra("LIST");
		adapter.setOnlineList(count, list);
	}

}
